package com.hong.chapter9;

import java.util.stream.Stream;

/**
 * sleep和wait的区别
 *
 * 1.sleep属于Thread 而wait属于对象
 * 2.wait 需要加同步而sleep不需要
 * 3.wait是不占用锁需要notify或notifyall唤醒，而sleep占用锁不需要唤醒时间到了自动进入就绪状态
 * 4.
 *
 */
public class DifferenceOfWaitAndSleep {

    private static Object LOCKS = new Object();

    public static void main(String[] args) {
        Stream.of("T1","T2").forEach(name->
            new Thread(name){
                @Override
                public void run() {
                    DifferenceOfWaitAndSleep.m2();
                }
            }.start()
        );
    }

    public static void m1(){
        synchronized (LOCKS){
            try {
                System.out.println("The Thread "+Thread.currentThread().getName()+" enter.");
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    public static void m2(){
        synchronized (LOCKS){
            try {
                System.out.println("The Thread "+Thread.currentThread().getName()+" enter.");
                LOCKS.wait(20000);
                LOCKS.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
